<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-17
 * Time: 16:15
 * 创建项目孵化订单
 */

namespace app\api\service\project;

use app\api\model\ProjectHatchOrder;
use app\api\model\System;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;


class HatchOrderSer extends Token
{
    /**
     * 1.判断会员
     * 2.判断是否有添加项目的权限
     * 3.有直接提示
     * 4.没有的话，创建订单
     * 5.返回支付number
     */
    // 用户id
    private $uid;

    // 入口方法
    public function createOrder()
    {
        $this->uid = self::getCurrentUid();
        self::judgeMemberOne();
        return $this->judgeProject();
    }

    // 判断项目孵化添加权限
    private function judgeProject()
    {
        $info = self::judgeProjectHatch();
        if($info) {
            throw new ParameterException([
                'errorCode' => 20001,
                'msg' => [
                    'hatch' => '您有创建项目的权限'
                ]
            ]);
        }
        return $this->createData();
    }

    // 创建项目订单
    private function createData()
    {
        // 删除未支付的订单
        ProjectHatchOrder::destroy(['user_id' => $this->uid , 'status' => 1]);
        $system = System::get(1);
        $user = User::get($this->uid);
        if(strtotime($user['member_end_time'].' 23:59:59') < time() || !$user['member_end_time']) {
            $price = $system['project_hatch_price'];
        } else {
            $price = $system['member_project_hatch_price'];
        }
        // 创建订单
        Db::startTrans();
        try{
            $mode = ProjectHatchOrder::create([
                'user_id' => $this->uid,
                'price' => $price,
                'order_no' => self::makeOrderNo()
            ]);
            $out_trade_no = '3you2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}